
#include "stdafx.h"
#include "IFile.h"

#pragma warning(disable : 4267)
#pragma warning(disable : 4996)

CIFile::CIFile()
{
	m_pFILE      = NULL;
	m_nErrorCode = ERR_NO;
	m_nSize      = 0;
}

CIFile::~CIFile()
{
	if(m_pFILE)
	{
		Close();
	}
}

bool CIFile::Open(const char* szFileName, const char *szMode)
{
	m_pFILE      = NULL;
	m_nErrorCode = ERR_NO;
	m_nSize      = 0;

	m_pFILE = fopen(szFileName, szMode);
	
	if(m_pFILE != NULL)
	{
		fseek(m_pFILE, 0, SEEK_END);
		m_nSize = ftell(m_pFILE);
		fseek(m_pFILE, 0, SEEK_SET);
		return true;
	}
	else
	{
		m_nErrorCode = ERR_HANDLE;
		return false;
	}
}

int CIFile::Read(void* pBuf, int nSize)
{
	if(m_pFILE&& (ftell(m_pFILE) + nSize <= m_nSize))
	{
		return fread(pBuf, nSize, 1, m_pFILE);
	}
	else
	{
		m_nErrorCode = ERR_READ;
	}

	return -1;
}

int CIFile::Write(void* pBuf, int nSize)
{
	if(m_pFILE)
	{
		return fwrite(pBuf, nSize, 1, m_pFILE);
	}
	else
	{
		m_nErrorCode = ERR_WRITE;
	}

	return -1;
}

bool CIFile::Close()
{
	if(m_pFILE)
	{
		return (fclose(m_pFILE) == 0);
	}
	else
	{
		m_nErrorCode = ERR_NO;
		m_nSize      = 0;
		
		return false;
	}
}

int CIFile::Error()
{
	return m_nErrorCode;
}

int CIFile::Size(int flag)
{
	if(m_pFILE)
	{
		if(flag == CISerial::LENGTH)
		{
			return m_nSize;
		}
		else if(flag == CISerial::LEFT)
		{
			return (m_nSize - ftell(m_pFILE));
		}
		else if(flag == CISerial::CURRENT)
		{
			return ftell(m_pFILE);
		}
	}

	return -1;			
}
